<template>
  <div class="app-container">

    <!-- 查询操作 -->
    <el-form :inline="true" class="filter-container filter">
      <el-form-item label="客户名称">
        <el-select v-model="listQuery.fsiteNo" :disabled="this.$store.state.user.fsiteLevel==3" clearable filterable placeholder="请选择客户名称">
            <el-option
              v-for="item in fsiteNoBelongOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
      </el-form-item>
      <el-form-item label="危废代码">
        <el-select v-model="listQuery.wasteCode" clearable filterable class="filter-item" placeholder="请选择危废代码">
          <el-option v-for="item in wasteCodeList" :key="item.id" :label="item.wasteCode" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="危废名称">
        <el-input v-model="listQuery.wasteName" clearable class="filter-item" style="width: 200px;"
          placeholder="请输入危废名称" />
      </el-form-item>
      <div>
        <el-form-item>
          <el-button round size="medium" class="filter-item"
            :style="{ background: buttonColor.lookup, color: buttonColor.color }" @click="handleFilter">查找</el-button>
          <el-button round size="medium" class="filter-item"
            :style="{ background: buttonColor.add, color: buttonColor.color }" @click="handleCreate">添加</el-button>

          <el-button round size="medium" class="filter-item"
            :style="{ background: buttonColor.cancellation, color: buttonColor.color }" @click="cancellation">注销
          </el-button>
          <el-button round size="medium" class="filter-item"
            :style="{ background: buttonColor.reduction, color: buttonColor.color }" @click="reduction">还原</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 查询结果 -->
    <el-table :height="buttonColor.clientHeight" v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。"
      border fit highlight-current-row :header-cell-style="tableColor" @selection-change="handleSelectionChange">
      <el-table-column align="center" :width="buttonColor.operationTwo" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{ color: buttonColor.edit, cursor: 'pointer' }" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" />
              编辑
            </div>
            <div :style="{ color: buttonColor.delete, cursor: 'pointer' }" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" />
              删除
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column :width="buttonColor.name" align="left" label="危废名称" prop="wasteName" />
      <el-table-column width="130" align="left" :formatter="wasteCodeFormat" label="危废代码" prop="wasteCode" />
      <el-table-column align="left" :formatter="wasteTypeFormat" label="危废类别编号" prop="wasteTypeCode" />
      <el-table-column width="300" align="left" :formatter="wasteTypeFormat1" label="危废类别名称" prop="wasteTypeName" />
      <el-table-column align="left" label="产生环节" prop="gongxu" />
      <el-table-column align="left" :width="buttonColor.state" label="状态" prop="status">
        <template slot-scope="scope">
          <span :style="{ color: buttonColor.statedisable }" v-if="scope.row.status === 0">{{
              scope.row.status | statusFilter
          }}</span>
          <span :style="{ color: buttonColor.statestart }" v-else>{{ scope.row.status | statusFilter }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog width="auto" top="0vh" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="危废名称" prop="wasteName">
              <el-input v-model="dataForm.wasteName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="危险废物" prop="attribute">
              <el-select v-model="dataForm.attribute" clearable filterable class="filter-item" placeholder="请选择是否危险废物">
                <el-option v-for="item in attributeList" :key="item.attributeCode" :label="item.attributeValue"
                  :value="Number(item.attributeCode)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="危废类别" prop="wasteType">
              <div style="display: flex;justify-content: flex-start;align-items: center;">
                <el-select v-model="dataForm.wasteType" clearable filterable class="filter-item" placeholder="请选择危废类别">
                  <el-option v-for="item in wasteTypeList" :key="item.wasteCategoryId" :label="item.categoryName"
                    :value="item.wasteCategoryId.toString()" />
                </el-select>
                <i class="el-icon-search selectI" @click="searchDialogWasteType()" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="危废代码" prop="wasteCode">
              <div style="display: flex;justify-content: flex-start;align-items: center;">
                <el-select v-model="dataForm.wasteCode" clearable filterable class="filter-item" placeholder="请选择危废代码">
                  <el-option v-for="item in wasteCodeList" :key="item.id" :label="item.wasteCode"
                    :value="item.id.toString()" />
                </el-select>
                <i class="el-icon-search selectI" @click="searchDialogWasteCode()" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item style="width: 100% !important" class="text" label="主要成分" prop="component">
              <el-input v-model="dataForm.component" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item class="required" label="危险特性" prop="dangerpromptarray">
              <el-checkbox-group v-model="dataForm.dangerpromptarray" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="(item, index) in dangerpromptList" :label="item.attributeCode" :key="index">{{
                    item.attributeValue
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物质形态" prop="materialState">
              <el-input v-model="dataForm.materialState" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产生环节" prop="gongxu">
              <el-input v-model="dataForm.gongxu" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item style="width: 100% !important" class="text" label="描述" prop="remark">
              <el-input v-model="dataForm.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button round :style="{ background: buttonColor.cancel, color: buttonColor.colorone }"
          @click="dialogFormVisible = false">取消</el-button>
        <el-button round v-if="dialogStatus == 'create'"
          :style="{ background: buttonColor.confirm, color: buttonColor.color }" @click="createData">确定</el-button>
        <el-button round v-else :style="{ background: buttonColor.confirm, color: buttonColor.color }"
          @click="updateData">确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 危废类别组件 -->
    <wasteTypeDialog :wasteTypeVisible.sync="wasteTypeVisible" :tableColor="tableColor"
      @wasteTypeDialog="wasteTypeDialogValue" />
    <!-- 危废代码组件 -->
    <wasteCodeDialog :wasteCodeVisible.sync="wasteCodeVisible" :tableColor="tableColor"
      @wasteCodeDialog="wasteCodeDialogValue" />
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}

.el-button+.el-button {
  margin-left: 1px;
}
</style>

<script>
/**
 * 引入api
 * 引入组件
 */
import { listcustomWaste, createcustomWaste, updatecustomWaste, deletecustomWaste, setStatus } from '@/api/dangerousWaste/customWaste'
import { listcategoryMapping } from '@/api/dangerousWaste/categoryMapping'
import { listattributeValue } from '@/api/dangerousWaste/attributeValue'
import { listwasteCategory } from '@/api/dangerousWaste/wasteCategory'
import { fsiteOptionsByLevel } from '@/api/area'
import WasteTypeDialog from "@/components/wasteTypeDialog";
import WasteCodeDialog from "@/components/WasteCodeDialog";
import Pagination from '@/components/Pagination'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import moment from 'moment'

const statusMap = {
  0: '无效',
  1: '有效'
}

export default {
  name: 'WCustomWaste',
  // 使用组件
  components: { Pagination, WasteTypeDialog, WasteCodeDialog },
  // 表单状态过滤
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      fsiteNoBelongOptions: [], // 客户列表
      wasteCodeVisible: false, // 危废代码弹出框
      wasteTypeVisible: false, // 危废类别弹出框
      wasteCodeList: [], // 危废代码
      attributeList: [], // 危险废物
      dangerpromptList: [], // 危险特性
      wasteTypeList: [], // 危废类别
      tableColor, // 表格颜色
      titleColor, // 弹窗颜色
      buttonColor, // 按钮颜色
      list: null, // 查询表单数据
      total: 0, // 表单总条数
      listLoading: true, // 等待查询loading
      listQuery: { // 查询字段
        page: 1,
        limit: 20,
        fsiteNo: this.$store.state.user.fsiteNo,
        wasteName: undefined,
        wasteCode: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: { // 添加，编辑字段
        fsiteNo: undefined,
        attribute: undefined,
        wasteName: undefined,
        wasteType: undefined,
        wasteTypeName: undefined,
        wasteCode: undefined,
        status: undefined,
        description: undefined,
        dangerprompt: undefined,
        dangerpromptarray: [],
        remark: undefined,
        gongxu: undefined,
        component: undefined,
        materialState: undefined,
        id: undefined
      },
      dialogFormVisible: false, // 添加，编辑弹窗是否显示
      dialogStatus: '', // 判断弹窗是添加/编辑
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: { // 表单提交规则
        attribute: [
          { required: true, message: '危险废物不能为空' },
          { type: 'number', message: '危险废物必须为数字值' },
        ],
        wasteCode: [
          { required: true, message: '危废代码不能为空' },
        ],
        wasteName: [
          { required: true, message: '危废名称不能为空' },
        ],
        wasteType: [
          { required: true, message: '危废类别不能为空' },
        ],
        dangerpromptarray: [
          { required: true, message: '危险特性不能为空' },
        ],
      }
    }
  },
  created() {
    this.getList()
    // 客户列表
    fsiteOptionsByLevel(3)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })
    // 危废代码
    listcategoryMapping(this.listQuery)
      .then(response => {
        this.wasteCodeList = response.data.data.list
      })
      .catch(() => {
        this.wasteCodeList = []
      })
    // 危险废物
    listattributeValue({ itemId: 409 })
      .then(response => {
        this.attributeList = response.data.data.list
      })
      .catch(() => {
        this.attributeList = []
      })

    // 危险特性
    listattributeValue({ itemId: -11 })
      .then(response => {
        this.dangerpromptList = response.data.data.list
      })
      .catch(() => {
        this.dangerpromptList = []
      })

    // 危废类别
    listwasteCategory({ limit: -1 })
      .then(response => {
        this.wasteTypeList = response.data.data.list
      })
      .catch(() => {
        this.wasteTypeList = []
      })

  },
  methods: {
    // 危险特性多选
    handleCheckedCitiesChange(value) {
      console.log('value', value);
    },
    // 危废代码弹出框--组件
    searchDialogWasteCode() {
      this.wasteCodeVisible = true;
    },
    // 危废代码返回数据--调用组件返回
    wasteCodeDialogValue(value) {
      this.dataForm.wasteCode = value.info.id.toString()
    },
    // 危废类别弹出框--组件
    searchDialogWasteType() {
      this.wasteTypeVisible = true;
    },
    // 弹出框返回数据--调用组件返回
    wasteTypeDialogValue(value) {
      this.dataForm.wasteType = value.info.wasteCategoryId.toString()
    },
    // 注销
    cancellation() {
      if (this.multipleSelection.length > 0) {
        let temp = []
        this.multipleSelection.forEach((item) => {
          temp.push(item.id)
        })
        setStatus({ ids: temp, status: 0 })
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '注销成功'
            })
            this.list.forEach(items => {
              if (temp.includes(items.id)) {
                items.status = 0
              }
            })

          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      } else {
        this.$notify.error({
          title: '失败',
          message: '至少选择一条数据'
        })
      }
    },
    // 还原
    reduction() {
      if (this.multipleSelection.length > 0) {
        let temp = []
        this.multipleSelection.forEach((item) => {
          temp.push(item.id)
        })
        setStatus({ ids: temp, status: 1 })
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '还原成功'
            })
            this.list.forEach(items => {
              if (temp.includes(items.id)) {
                items.status = 1
              }
            })
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      } else {
        this.$notify.error({
          title: '失败',
          message: '至少选择一条数据'
        })
      }
    },
    // 多选事件
    handleSelectionChange(val) {
      console.log('val', val);
      this.multipleSelection = val;
    },
    // 危废代码
    wasteCodeFormat(row) {
      if (this.wasteCodeList.length > 0) {
        for (let i = 0; i < this.wasteCodeList.length; i++) {
          if (row.wasteCode == this.wasteCodeList[i].id) {
            return this.wasteCodeList[i].wasteCode
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 危废类别编号
    wasteTypeFormat(row) {
      if (this.wasteTypeList.length > 0) {
        for (let i = 0; i < this.wasteTypeList.length; i++) {
          if (row.wasteType == this.wasteTypeList[i].wasteCategoryId) {
            return this.wasteTypeList[i].categoryCode
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 危废类别名称
    wasteTypeFormat1(row) {
      if (this.wasteTypeList.length > 0) {
        for (let i = 0; i < this.wasteTypeList.length; i++) {
          if (row.wasteType == this.wasteTypeList[i].wasteCategoryId) {
            return this.wasteTypeList[i].categoryName
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 时间回显
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取数据
    getList() {
      this.listLoading = true
      listcustomWaste(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 查找
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加时重置表单
    resetForm() {
      this.dataForm = {
        attribute: undefined,
        wasteName: undefined,
        wasteType: undefined,
        wasteCode: undefined,
        status: undefined,
        description: undefined,
        dangerprompt: undefined,
        dangerpromptarray: [],
        remark: undefined,
        gongxu: undefined,
        component: undefined,
        materialState: undefined,
        id: undefined
      }
    },
    // 打开添加弹窗
    handleCreate() {
      this.resetForm()
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.status = 1
          createcustomWaste(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加危废资料成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    // 打开编辑弹窗
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updatecustomWaste(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新危废资料成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否要删除危废资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletecustomWaste(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除危废资料成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    // 表单序号
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
